<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"llmysnow.top","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="v-show 和 v-if 区别 v-show 通过 CSS display 控制显示和隐藏 v-if 通过判断组件真实渲染和销毁，而不是显示和隐藏 频繁切换显示状态用 v-show，否则用 v-if  v-if   当 v-if 与 v-for 一起使用时，v-for 具有比 v-if 更高的优先级，意味着：v-if 将分别重复运行于每个 v-for 循环中，会造成性能问题。所以，不推荐 v-i">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue2 面试题">
<meta property="og:url" content="http://llmysnow.top/posts/920f26b5/index.html">
<meta property="og:site_name" content="奇幻的梦之旅">
<meta property="og:description" content="v-show 和 v-if 区别 v-show 通过 CSS display 控制显示和隐藏 v-if 通过判断组件真实渲染和销毁，而不是显示和隐藏 频繁切换显示状态用 v-show，否则用 v-if  v-if   当 v-if 与 v-for 一起使用时，v-for 具有比 v-if 更高的优先级，意味着：v-if 将分别重复运行于每个 v-for 循环中，会造成性能问题。所以，不推荐 v-i">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/jslearn-img/vue%E6%B8%B2%E6%9F%93%E6%9B%B4%E6%96%B0%E6%B5%81%E7%A8%8B%E5%9B%BE.png">
<meta property="og:image" content="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/847306f303ab4177891b56cccff1ebd3~tplv-k3u1fbpfcp-watermark.image">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/jslearn-img/diff%E7%AE%97%E6%B3%95%E6%A6%82%E8%BF%B0.png">
<meta property="og:image" content="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d84848aa035b4472b4d3f8e4b0d708c5~tplv-k3u1fbpfcp-watermark.awebp">
<meta property="article:published_time" content="2022-04-23T11:27:04.398Z">
<meta property="article:modified_time" content="2022-04-23T11:27:47.138Z">
<meta property="article:author" content="LiLyn">
<meta property="article:tag" content="Vue">
<meta property="article:tag" content="diff算法">
<meta property="article:tag" content="响应式原理">
<meta property="article:tag" content="nextTick">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/lilyn/pic/raw/master/jslearn-img/vue%E6%B8%B2%E6%9F%93%E6%9B%B4%E6%96%B0%E6%B5%81%E7%A8%8B%E5%9B%BE.png">

<link rel="canonical" href="http://llmysnow.top/posts/920f26b5/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Vue2 面试题 | 奇幻的梦之旅</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="奇幻的梦之旅" type="application/atom+xml">
</head>
<!--即时预加载技术，在用户点击之前预先加载页面-->
<script src="https://cdn.jsdelivr.net/gh/TRHX/CDN-for-itrhx.com@2.0.2/js/instantclick-1.2.2.js" type="module"></script>
<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
	  <!--<a target="_blank" rel="noopener" href="https://github.com/llwodexue" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>-->
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">奇幻的梦之旅</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">http://llmysnow.top/</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://llmysnow.top/posts/920f26b5/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/logo.jpg">
      <meta itemprop="name" content="LiLyn">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="奇幻的梦之旅">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Vue2 面试题
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-04-23 19:27:04" itemprop="dateCreated datePublished" datetime="2022-04-23T19:27:04+08:00">2022-04-23</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Vue/" itemprop="url" rel="index"><span itemprop="name">Vue</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>14k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>13 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="v-show-和-v-if-区别"><a href="#v-show-和-v-if-区别" class="headerlink" title="v-show 和 v-if 区别"></a>v-show 和 v-if 区别</h2><ul>
<li><code>v-show</code> 通过 CSS display 控制显示和隐藏</li>
<li><code>v-if</code> 通过判断组件真实渲染和销毁，而不是显示和隐藏</li>
<li>频繁切换显示状态用 <code>v-show</code>，否则用 <code>v-if</code></li>
</ul>
<p><code>v-if</code> </p>
<ul>
<li>当 <code>v-if</code> 与 <code>v-for</code> 一起使用时，<code>v-for</code> 具有比 <code>v-if</code> 更高的优先级，意味着：<code>v-if</code> 将分别重复运行于每个 <code>v-for</code> 循环中，会造成性能问题。所以，不推荐 <code>v-if</code> 和 <code>v-for</code> 同时使用</li>
</ul>
<a id="more"></a>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> compiler = <span class="built_in">require</span>(<span class="string">&#x27;vue-template-compiler&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> res = compiler.compile(<span class="string">`&lt;div v-if=&quot;true&quot; v-for=&quot;i in 3&quot;&gt;&#123;&#123;message&#125;&#125;&lt;/div&gt;`</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> (<span class="built_in">this</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> renderList(<span class="number">3</span>, <span class="function"><span class="keyword">function</span>(<span class="params">i</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span> ? createElement(<span class="string">&#x27;div&#x27;</span>, [createTextVNode(toString(message))]) : createEmptyVNode()</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>v-show</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> compiler = <span class="built_in">require</span>(<span class="string">&#x27;vue-template-compiler&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> res = compiler.compile(<span class="string">`&lt;p v-show=&quot;flag === &#x27;a&#x27;&quot;&gt;A&lt;/p&gt;`</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> (<span class="built_in">this</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> createElement(</span><br><span class="line">    <span class="string">&#x27;p&#x27;</span>,</span><br><span class="line">    &#123;</span><br><span class="line">      directives: [</span><br><span class="line">        &#123; <span class="attr">name</span>: <span class="string">&#x27;show&#x27;</span>, <span class="attr">rawName</span>: <span class="string">&#x27;v-show&#x27;</span>, <span class="attr">value</span>: flag === <span class="string">&#x27;a&#x27;</span>, <span class="attr">expression</span>: <span class="string">&quot;flag === &#x27;a&#x27;&quot;</span> &#125;,</span><br><span class="line">      ],</span><br><span class="line">    &#125;,</span><br><span class="line">    [createTextVNode(<span class="string">&#x27;A&#x27;</span>)]</span><br><span class="line">  )</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// v-show 操作的是样式 https://github.com/vuejs/vue/blob/dev/src/platforms/web/runtime/directives/show.js</span></span><br><span class="line">bind (el: any, &#123; value &#125;: VNodeDirective, <span class="attr">vnode</span>: VNodeWithData) &#123;</span><br><span class="line">  vnode = locateNode(vnode)</span><br><span class="line">  <span class="keyword">const</span> transition = vnode.data &amp;&amp; vnode.data.transition</span><br><span class="line">  <span class="keyword">const</span> originalDisplay = el.__vOriginalDisplay =</span><br><span class="line">    el.style.display === <span class="string">&#x27;none&#x27;</span> ? <span class="string">&#x27;&#x27;</span> : el.style.display</span><br><span class="line">  <span class="keyword">if</span> (value &amp;&amp; transition) &#123;</span><br><span class="line">    vnode.data.show = <span class="literal">true</span></span><br><span class="line">    enter(vnode, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      el.style.display = originalDisplay</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    el.style.display = value ? originalDisplay : <span class="string">&#x27;none&#x27;</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="为何在-v-for-中用-key"><a href="#为何在-v-for-中用-key" class="headerlink" title="为何在 v-for 中用 key"></a>为何在 v-for 中用 key</h2><ul>
<li>必须用 <code>key</code>，且不能是 <code>index</code> 和 <code>random</code></li>
<li><code>diff</code> 算法中通过 <code>tag</code> 和 <code>key</code> 来判断，是否是 <code>sameNode</code></li>
<li>减少渲染次数，提升渲染性能</li>
</ul>
<h2 id="描述-Vue-组件生命周期（父子组件）"><a href="#描述-Vue-组件生命周期（父子组件）" class="headerlink" title="描述 Vue 组件生命周期（父子组件）"></a>描述 Vue 组件生命周期（父子组件）</h2><ul>
<li><p><code>beforeCreate</code> 在初始化事件生命周期之后，数据被观测（observer）之前调用</p>
</li>
<li><p><code>created</code> 实例已经创建完成之后被调用</p>
<p>可以进行一些数据、资源请求。在这个阶段无法与 DOM 进行交互，如果非想要，可以通过 <code>$nextTick</code> 访问</p>
</li>
<li><p><code>beforeMount</code> 在 DOM 挂载之前被调用，相关的 <code>render</code> 函数首次被调用（如果有 <code>template</code> 会转换成 <code>render</code> 函数）</p>
<p>在此时也可以对数据进行更改，不会触发 <code>updated</code></p>
</li>
<li><p><code>mounted</code> 创建 <code>vm.$el</code> 并替换 <code>el</code>，并在挂载之后调用该钩子</p>
<p>可以访问到 DOM 节点，使用 <code>$refs</code> 属性对 DOM 进行操作，也可以像后台发送请求，拿到返回数据</p>
</li>
<li><p><code>beforeUpdate</code> 数据更新时调用，发生在虚拟 DOM 重新渲染和和打补丁之前</p>
<p>可以在这个钩子中进一步地更改状态，这不会触发附加的重新渲染</p>
</li>
<li><p><code>updated</code> 由于数据更改导致虚拟 DOM 重新渲染和打补丁，在这之后会调用该钩子</p>
<p>避免在此期间更改状态，可能会导致更新无限循环</p>
</li>
<li><p><code>beforeDestroy</code> 实例销毁之前调用</p>
</li>
<li><p><code>destroyed </code> Vue 实例销毁后调用，调用后，Vue 实例所有东西都会解绑定，所有事件监听会被移除，所有子实例也会被销毁</p>
<p>可以执行一些优化操作，清除定时器，解除绑定事件</p>
</li>
</ul>
<p>注意：除了 <code>beforeCreate</code> 和 <code>created</code> 钩子之外，其他钩子均在服务器端渲染期间不调用</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Vue.prototype._init = <span class="function"><span class="keyword">function</span> (<span class="params">options?: <span class="built_in">Object</span></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">  initLifecycle(vm)</span><br><span class="line">  initEvents(vm) <span class="comment">// 初始化事件相关的属性</span></span><br><span class="line">  initRender(vm) <span class="comment">// vm 添加了一些虚拟 dom、slot 等相关的属性和方法</span></span><br><span class="line">  callHook(vm, <span class="string">&#x27;beforeCreate&#x27;</span>)</span><br><span class="line">  initInjections(vm)</span><br><span class="line">  initState(vm) <span class="comment">// props、methods、data、watch、computed等数据初始化</span></span><br><span class="line">  initProvide(vm)</span><br><span class="line">  callHook(vm, <span class="string">&#x27;created&#x27;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>mounted</code> （渲染完成）执行顺序是先子后父</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">patch</span>(<span class="params">oldVnode, vnode, hydrating, removeOnly</span>) </span>&#123;</span><br><span class="line">   <span class="comment">// 定义收集所有组件的insert hook方法的数组</span></span><br><span class="line">  <span class="keyword">const</span> insertedVnodeQueue = []</span><br><span class="line">  <span class="keyword">if</span> (isUndef(oldVnode)) &#123;</span><br><span class="line">    createElm(vnode, insertedVnodeQueue)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createElm</span>(<span class="params">vnode, insertedVnodeQueue, ...</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// createChildren会递归创建子组件（递归createElm）</span></span><br><span class="line">  createChildren(vnode, children, insertedVnodeQueue)</span><br><span class="line">  <span class="keyword">if</span> (isDef(data)) &#123;</span><br><span class="line">    <span class="comment">// 执行所有的create钩子</span></span><br><span class="line">    invokeCreateHooks(vnode, insertedVnodeQueue)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">invokeCreateHooks</span> (<span class="params">vnode, insertedVnodeQueue</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 把vnode push到insertedVnodeQueue</span></span><br><span class="line">  <span class="keyword">if</span> (isDef(i.insert)) insertedVnodeQueue.push(vnode)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 调用insert方法把DOM插入到父节点，因为是递归调用，子元素会优先调用insert</span></span><br><span class="line">insert(parentElm, vnode.elm, refElm)</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">invokeInsertHook</span>(<span class="params">vnode, queue, initial</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 依次调用insert方法</span></span><br><span class="line">  queue[i].data.hook.insert(queue[i])</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> componentVNodeHooks = &#123;</span><br><span class="line">  <span class="comment">// 依次执行 mounted 方法</span></span><br><span class="line">  <span class="function"><span class="title">insert</span>(<span class="params">vnode: MountedComponentVNode</span>)</span> &#123;</span><br><span class="line">    callHook(componentInstance, <span class="string">&#x27;mounted&#x27;</span>)</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>$destroy</code> （销毁完成）执行顺序是先子后父</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Vue.prototype.$destroy = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  callHook(vm, <span class="string">&#x27;beforeDestroy&#x27;</span>)</span><br><span class="line">   <span class="comment">// 递归触发子组件销毁钩子函数</span></span><br><span class="line">  vm.__patch__(vm._vnode, <span class="literal">null</span>)</span><br><span class="line">  callHook(vm, <span class="string">&#x27;destroyed&#x27;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Vue-组件如何通讯"><a href="#Vue-组件如何通讯" class="headerlink" title="Vue 组件如何通讯"></a>Vue 组件如何通讯</h2><ul>
<li>父 -&gt; 子通过 <code>props</code>，子 -&gt; 父通过 <code>$on $emit</code></li>
<li>在父组件中提供数据子组件进行消费 <code>provide</code>、<code>inject</code></li>
<li><code>ref</code> 获取实例的方式调用组件的属性或方法</li>
<li>自定义事件 <code>event.$on</code>、<code>event.$off</code>、<code>event.$emit</code></li>
<li><code>vuex</code> 状态管理实现通信</li>
</ul>
<h2 id="描述组件渲染和更新过程"><a href="#描述组件渲染和更新过程" class="headerlink" title="描述组件渲染和更新过程"></a>描述组件渲染和更新过程</h2><ul>
<li>生成 <code>render</code> 函数，其生成一个 <code>vnode</code>，它会 <code>touch</code> 触发 <code>getter</code> 进行收集依赖</li>
<li>在模板中哪个被引用了就会将其用 <code>Watcher</code> 观察起来，发生了 <code>setter</code> 也会将其 <code>Watcher</code> 起来</li>
<li>如果之前已经被 <code>Watcher</code> 观察起来，发生更新进行重新渲染</li>
</ul>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/jslearn-img/vue%E6%B8%B2%E6%9F%93%E6%9B%B4%E6%96%B0%E6%B5%81%E7%A8%8B%E5%9B%BE.png"></p>
<h2 id="双向数据绑定-v-model-的实现原理"><a href="#双向数据绑定-v-model-的实现原理" class="headerlink" title="双向数据绑定 v-model 的实现原理"></a>双向数据绑定 v-model 的实现原理</h2><p><code>v-model</code>本质上是语法糖，<code>v-model</code> 在内部为不同的输入元素使用不同的属性并抛出不同的事件</p>
<ul>
<li><code>text</code> 和 <code>textarea</code> 元素使用 value 属性和 input 事件</li>
<li><code>checkbox</code> 和 <code>radio</code> 使用 checked 属性和 change 事件</li>
<li><code>select</code> 字段将 value 作为 prop 并将 change 作为事件</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> compiler = <span class="built_in">require</span>(<span class="string">&#x27;vue-template-compiler&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> res = compiler.compile(<span class="string">`&lt;input v-model=&quot;name&quot; type=&quot;text&quot; /&gt;`</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> (<span class="built_in">this</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> createElement(<span class="string">&#x27;input&#x27;</span>, &#123;</span><br><span class="line">    directives: [&#123; <span class="attr">name</span>: <span class="string">&#x27;model&#x27;</span>, <span class="attr">rawName</span>: <span class="string">&#x27;v-model&#x27;</span>, <span class="attr">value</span>: name, <span class="attr">expression</span>: <span class="string">&#x27;name&#x27;</span> &#125;],</span><br><span class="line">    attrs: &#123; <span class="attr">type</span>: <span class="string">&#x27;text&#x27;</span> &#125;,</span><br><span class="line">    domProps: &#123; <span class="attr">value</span>: name &#125;,</span><br><span class="line">    on: &#123;</span><br><span class="line">      input: <span class="function"><span class="keyword">function</span>(<span class="params">$event</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> ($event.target.composing) <span class="keyword">return</span></span><br><span class="line">        name = $event.target.value</span><br><span class="line">      &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="对-MVVM-的理解"><a href="#对-MVVM-的理解" class="headerlink" title="对 MVVM 的理解"></a>对 MVVM 的理解</h2><ul>
<li><code>Model</code>：代表数据模型，也可以在 <code>Model</code> 中定义数据修改和操作的业务逻辑。我们可以把 <code>Model</code> 称为数据层，因为它仅仅关注数据本身，不关心任何行为</li>
<li><code>View</code>：用户操作界面。当 <code>ViewModel</code> 对 <code>Model</code> 进行更新的时候，会通过数据绑定更新到 <code>View</code></li>
<li><code>ViewModel</code>：业务逻辑层，<code>View</code> 需要什么数据，<code>ViewModel</code> 要提供这个数据；<code>View</code> 有某些操作，<code>ViewModel</code> 就要响应这些操作</li>
</ul>
<p><strong>总结</strong>： <code>MVVM</code>模式简化了界面与业务的依赖，解决了数据频繁更新。<code>MVVM</code> 在使用当中，利用双向绑定技术，使得 <code>Model</code> 变化时，<code>ViewModel</code> 会自动更新，而 <code>ViewModel</code> 变化时，<code>View</code> 也会自动变化</p>
<h2 id="computed-和-watch-的区别"><a href="#computed-和-watch-的区别" class="headerlink" title="computed 和 watch 的区别"></a>computed 和 watch 的区别</h2><p><code>computed</code>：</p>
<ul>
<li><code>computed</code> 具有缓存性，<code>computed</code> 的值在 <code>getter</code> 执行后是会缓存的，只有它依赖的属性值改变之后，下一次获取 <code>computed</code> 的值时才会重新调用对应的 <code>getter</code> 来计算</li>
<li><code>computed</code> 适用于比较消耗性能的计算场景，可以提高性能</li>
</ul>
<p><code>watch</code>：</p>
<ul>
<li>更多的是观察作用，类似于数据监听的回调函数，用于观察 <code>props</code>、<code>$emit</code> 或本组件的值，当数据变化时来执行回调进行后续操作</li>
<li>无缓存性，页面重新渲染时值不变化也会执行</li>
</ul>
<p><code>computed</code> 和 <code>watch</code> 都支持对象的写法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">vm.$watch(<span class="string">&#x27;obj&#x27;</span>, &#123;</span><br><span class="line">  deep: <span class="literal">true</span>, <span class="comment">// 深度遍历</span></span><br><span class="line">  immediate: <span class="literal">true</span>, <span class="comment">// 立即触发</span></span><br><span class="line">  handler: <span class="function"><span class="keyword">function</span>(<span class="params">val, oldVal</span>) </span>&#123;&#125;, <span class="comment">// 执行的函数</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">var</span> vm = <span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  data: &#123; <span class="attr">a</span>: <span class="number">1</span> &#125;,</span><br><span class="line">  computed: &#123;</span><br><span class="line">    aPlus: &#123;</span><br><span class="line">      <span class="comment">// this.aPlus 时触发</span></span><br><span class="line">      get: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.a + <span class="number">1</span></span><br><span class="line">      &#125;,</span><br><span class="line">      <span class="comment">// this.aPlus = 1 时触发</span></span><br><span class="line">      set: <span class="function"><span class="keyword">function</span>(<span class="params">v</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.a = v - <span class="number">1</span></span><br><span class="line">      &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="为何组件-data-必须是一个函数"><a href="#为何组件-data-必须是一个函数" class="headerlink" title="为何组件 data 必须是一个函数"></a>为何组件 data 必须是一个函数</h2><ul>
<li>一个组件被复用多次的话，也就是创建多个实例。本质上，这些实例用的都是同一个构造函数，如果 <code>data</code> 是对象的话（引用数据类型），会影响到所有实例</li>
<li>为了组件不同实例 <code>data</code> 不冲突，<code>data</code> 必须是一个函数</li>
</ul>
<h2 id="自定义-v-model"><a href="#自定义-v-model" class="headerlink" title="自定义 v-model"></a>自定义 v-model</h2><p><code>v-model</code> 可以看成是 <code>value + input</code> 方法的语法糖</p>
<ul>
<li>自定义：自己写 <code>model</code> 属性，里面放上 <code>prop</code> 和 <code>event</code></li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">:value</span>=<span class="string">&quot;text&quot;</span> @<span class="attr">input</span>=<span class="string">&quot;$emit(&#x27;change&#x27;, $event.target.value)&quot;</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line">  model: &#123;</span><br><span class="line"><span class="javascript">    prop: <span class="string">&#x27;text&#x27;</span>,</span></span><br><span class="line"><span class="javascript">    event: <span class="string">&#x27;change&#x27;</span>,</span></span><br><span class="line">  &#125;,</span><br><span class="line">  props: &#123;</span><br><span class="line"><span class="javascript">    text: <span class="built_in">String</span>,</span></span><br><span class="line">  &#125;,</span><br><span class="line">&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="相同逻辑如何抽离"><a href="#相同逻辑如何抽离" class="headerlink" title="相同逻辑如何抽离"></a>相同逻辑如何抽离</h2><ul>
<li><code>Vue.mixin</code> ，给组件每个生命周期、函数都混入一些公共逻辑</li>
<li><code>mixin</code> 混入的钩子函数会先于组件内的钩子函数执行，并且在遇到同名选项时也会有选择性进行合并</li>
</ul>
<h2 id="何时使用异步组件"><a href="#何时使用异步组件" class="headerlink" title="何时使用异步组件"></a>何时使用异步组件</h2><p>核心就是把组件变成一个函数，依赖 <code>import()</code> 语法，可以实现文件的分割加载</p>
<ul>
<li>加载大组件</li>
<li>路由异步加载</li>
</ul>
<h2 id="何时使用-keep-alive"><a href="#何时使用-keep-alive" class="headerlink" title="何时使用 keep-alive"></a>何时使用 keep-alive</h2><p>常用的两个属性：<code>include</code>、<code>exclude</code>，允许组件有条件的进行缓存</p>
<p>两个生命周期：<code>activated</code>、<code>deactivated</code>，用来得知当前组件是否处于活跃状态</p>
<ul>
<li>缓存组件实例，用于保留组件状态或避免重复渲染</li>
<li>多个静态 Tab 页的切换时，来优化性能</li>
</ul>
<h2 id="何时需要使用-beforeDestory"><a href="#何时需要使用-beforeDestory" class="headerlink" title="何时需要使用 beforeDestory"></a>何时需要使用 beforeDestory</h2><ul>
<li>解绑自定义事件 <code>event.$off</code></li>
<li>清除定时器</li>
<li>解绑自定义的 DOM 事件，如：<code>window</code>、<code>scroll</code> 等</li>
</ul>
<h2 id="action-和-mutation-有何区别"><a href="#action-和-mutation-有何区别" class="headerlink" title="action 和 mutation 有何区别"></a>action 和 mutation 有何区别</h2><ul>
<li><code>action</code> 中可以处理异步，<code>mutation</code> 中不可以</li>
<li><code>mutation</code> 做的是原子操作，<code>action</code> 可以整合多个 <code>mutation</code></li>
</ul>
<h2 id="vue-router-常用的路由模式"><a href="#vue-router-常用的路由模式" class="headerlink" title="vue-router 常用的路由模式"></a>vue-router 常用的路由模式</h2><p><strong>hash 路由</strong></p>
<ul>
<li><code>hash</code> 变化会触发网页跳转，即浏览器的前进、后退</li>
<li><code>hash</code> 变化不会刷新页面，<code>SPA</code> 必需的特点</li>
<li><code>hash</code> 永远不会提交到 <code>server</code> 端（前端自生自灭）</li>
</ul>
<p><strong>history 路由</strong></p>
<ul>
<li>用 <code>url</code> 规范的路由，但跳转时不刷新页面</li>
<li>需要 <code>server</code> 端配合，可参考：<a target="_blank" rel="noopener" href="https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90">后端配置例子</a></li>
<li><code>pushState</code> 不会触发 <code>hashchange</code> 事件，<code>popstate</code> 事件只会在浏览器某些行为下触发，比如点击后退、前进按钮</li>
</ul>
<h2 id="vnode-描述一个-DOM-结构"><a href="#vnode-描述一个-DOM-结构" class="headerlink" title="vnode 描述一个 DOM 结构"></a>vnode 描述一个 DOM 结构</h2><ul>
<li>Vue 中的真实 DOM</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;div1&quot;</span> <span class="attr">class</span>=<span class="string">&quot;container&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">p</span>&gt;</span>vdom<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">ul</span> <span class="attr">style</span>=<span class="string">&quot;font-size: 20px;&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">li</span>&gt;</span>a<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>Vue 中的虚拟 DOM</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  tag: <span class="string">&#x27;div&#x27;</span>,</span><br><span class="line">  props: &#123;</span><br><span class="line">    className: <span class="string">&#x27;container&#x27;</span>,</span><br><span class="line">    id: <span class="string">&#x27;div1&#x27;</span>,</span><br><span class="line">  &#125;,</span><br><span class="line">  children: [</span><br><span class="line">    &#123;</span><br><span class="line">      tag: <span class="string">&#x27;p&#x27;</span>,</span><br><span class="line">      children: <span class="string">&#x27;dom&#x27;</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      tag: <span class="string">&#x27;ul&#x27;</span>,</span><br><span class="line">      props: &#123; <span class="attr">style</span>: <span class="string">&#x27;font-size: 20px&#x27;</span> &#125;,</span><br><span class="line">      children: [&#123; <span class="attr">tag</span>: <span class="string">&#x27;li&#x27;</span>, <span class="attr">children</span>: <span class="string">&#x27;a&#x27;</span> &#125;],</span><br><span class="line">    &#125;,</span><br><span class="line">  ],</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="数据响应式原理"><a href="#数据响应式原理" class="headerlink" title="数据响应式原理"></a>数据响应式原理</h2><p><strong>核心 API</strong>：<code>Object.defineProperty</code></p>
<ul>
<li><p>存在一些问题，Vue 3.0 启动 <code>Proxy</code></p>
<p><code>Proxy</code> 可以原生支持监听数组变化</p>
<p>但是 <code>Proxy</code> 兼容性不好，且无法 <code>polyfill</code></p>
</li>
</ul>
<p><strong>问题</strong></p>
<ul>
<li>深度监听，需要递归到底，一次性计算量大</li>
<li>无法监听新增属性/删除属性（<code>Vue.set</code>、<code>Vue.delete</code>）</li>
<li>不能监听数组变化（重新定义原型，重写 <code>push</code>、<code>pop</code> 等方法）</li>
</ul>
<p><strong>简单实现 Vue 中的 defineReactive</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 触发更新视图</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">updateView</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;视图更新&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 重新定义数组原型</span></span><br><span class="line"><span class="keyword">const</span> arrayProto = <span class="built_in">Array</span>.prototype</span><br><span class="line"><span class="comment">// 创建新对象，原型指向 arrayProto ，再扩展新的方法不会影响原型</span></span><br><span class="line"><span class="keyword">const</span> arrayMethods = <span class="built_in">Object</span>.create(arrayProto)</span><br><span class="line">;[<span class="string">&#x27;push&#x27;</span>, <span class="string">&#x27;pop&#x27;</span>, <span class="string">&#x27;shift&#x27;</span>, <span class="string">&#x27;unshift&#x27;</span>, <span class="string">&#x27;splice&#x27;</span>, <span class="string">&#x27;sort&#x27;</span>, <span class="string">&#x27;reverse&#x27;</span>].forEach(<span class="function"><span class="params">method</span> =&gt;</span> &#123;</span><br><span class="line">  arrayMethods[method] = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    arrayProto[method].call(<span class="built_in">this</span>, ...arguments) <span class="comment">// 原始操作</span></span><br><span class="line">    updateView() <span class="comment">// 触发视图更新</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 重新定义属性，监听起来</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">defineReactive</span>(<span class="params">target, key, value</span>) </span>&#123;</span><br><span class="line">  observer(value) <span class="comment">// 进行监听</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 不可枚举的不用监听</span></span><br><span class="line">  <span class="keyword">const</span> property = <span class="built_in">Object</span>.getOwnPropertyDescriptor(target, key)</span><br><span class="line">  <span class="keyword">if</span> (property &amp;&amp; property.configurable === <span class="literal">false</span>) <span class="keyword">return</span></span><br><span class="line">  <span class="built_in">Object</span>.defineProperty(target, key, &#123;</span><br><span class="line">    <span class="function"><span class="title">get</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> value</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="function"><span class="title">set</span>(<span class="params">newValue</span>)</span> &#123;</span><br><span class="line">      <span class="keyword">if</span> (newValue !== value) &#123;</span><br><span class="line">        observer(newValue) <span class="comment">// 值修改后进行监听</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// value 一直在闭包中，此处设置完之后，再 get 时也是会获取最新的值</span></span><br><span class="line">        value = newValue</span><br><span class="line">        updateView() <span class="comment">// 触发更新视图</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 监测数据的变化</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">observer</span>(<span class="params">target</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 不是对象或数组（vue 是判断是否是数组、纯粹对象、可扩展对象）</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> target !== <span class="string">&#x27;object&#x27;</span> || target === <span class="literal">null</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> target</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 不要这样写，污染全局的 Array 原型</span></span><br><span class="line">  <span class="comment">/* Array.prototype.push = function () &#123;</span></span><br><span class="line"><span class="comment">      updateView()</span></span><br><span class="line"><span class="comment">  &#125; */</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(target)) &#123;</span><br><span class="line">    target.__proto__ = arrayMethods</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 重新定义各个属性（for in 也可以遍历数组）</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> target) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!<span class="built_in">Object</span>.hasOwnProperty.call(target, key)) <span class="keyword">return</span></span><br><span class="line">    defineReactive(target, key, target[key])</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> data = &#123;</span><br><span class="line">  name: <span class="string">&#x27;zhangsan&#x27;</span>,</span><br><span class="line">  age: <span class="number">20</span>,</span><br><span class="line">  info: &#123;</span><br><span class="line">    address: <span class="string">&#x27;北京&#x27;</span>, <span class="comment">// 需要深度监听</span></span><br><span class="line">  &#125;,</span><br><span class="line">  nums: [<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>],</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">observer(data)</span><br><span class="line"></span><br><span class="line">data.name = <span class="string">&#x27;lisi&#x27;</span></span><br><span class="line">data.age = <span class="number">21</span></span><br><span class="line">data.info.address = <span class="string">&#x27;上海&#x27;</span> <span class="comment">// 深度监听</span></span><br><span class="line"><span class="comment">// data.x = &#x27;100&#x27; // 新增属性，监听不到 —— 所以有 Vue.set</span></span><br><span class="line"><span class="comment">// delete data.name // 删除属性，监听不到 —— 所有已 Vue.delete</span></span><br><span class="line">data.nums.push(<span class="number">4</span>) <span class="comment">// 监听数组</span></span><br></pre></td></tr></table></figure>

<h2 id="diff-算法"><a href="#diff-算法" class="headerlink" title="diff 算法"></a>diff 算法</h2><p>diff 算法过程：</p>
<ul>
<li>同级元素进行比较，再比较子节点</li>
<li>先判断一方有子节点，一方没有子节点情况（如果新的 <code>children</code> 没有子节点，将旧的子节点移除）</li>
<li>之后比较都有子节点的情况（核心 <code>diff</code>），递归比较子节点</li>
</ul>
<p>正常 <code>diff</code> 两个树的时间复杂度是 <code>O(n^3)</code>，但实际情况我们很少会跨级移动 DOM。所以，只有当新旧 <code>children</code> 都为多个子节点时才需要核心的 <code>diff</code> 算法进行同层级比较</p>
<ul>
<li>Vue2 核心 <code>diff</code> 算法采用了双端比较的算法，同时从新旧 <code>children</code> 的两端开始比较，借助 <code>key</code> 值找到可复用的节点，再进行相关操作。相比 React 的 <code>diff</code> 算法，同样情况可以减少移动节点次数，减少不必要的性能损耗</li>
<li>Vue3 核心 <code>diff</code> 算法采用了最长递增子序列</li>
</ul>
<p><img data-src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/847306f303ab4177891b56cccff1ebd3~tplv-k3u1fbpfcp-watermark.image" alt="img"></p>
<p>双端比较算法</p>
<ul>
<li>使用 <strong>旧列表</strong> 的头一个节点 <code>oldStartNode</code> 与 <strong>新列表</strong> 的头一个节点 <code>newStartNode</code> 对比</li>
<li>使用 <strong>旧列表</strong> 的最后一个节点 <code>oldEndNode</code> 与 <strong>新列表</strong> 的最后一个节点 <code>newEndNode</code> 对比</li>
<li>使用 <strong>旧列表</strong> 的头一个节点 <code>oldStartNode</code> 与 <strong>新列表</strong> 的最后一个节点 <code>newEndNode</code> 对比</li>
<li>使用 <strong>旧列表</strong> 的最后一个节点 <code>oldEndNode</code> 与 <strong>新列表</strong> 的头一个节点 <code>newStartNode</code> 对比</li>
</ul>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/jslearn-img/diff%E7%AE%97%E6%B3%95%E6%A6%82%E8%BF%B0.png"></p>
<p><strong>树 diff 的时间复杂度 O(n^3)</strong></p>
<ul>
<li><p>对于旧树上的点 E 来说，它要和新树上的所有点比较，复杂度为 <code>O(n)</code></p>
</li>
<li><p>点 E 在新树上没有找到，点 E 会被删除，然后遍历新树上的所有点找到对应点（X）去填空，复杂度增加到 <code>O(n^2)</code></p>
</li>
<li><p>这样的操作会在旧树的每个点进行，最终复杂度为 <code>O(n^3)</code></p>
<p>1000 个节点，要计算 1 亿次，算法不可用</p>
</li>
</ul>
<p><strong>优化时间复杂度到 O(n)</strong></p>
<ul>
<li>只比较同一层级，不跨级比较</li>
<li><code>tag</code> 不相同，则直接删掉重建，不再深度比较</li>
<li><code>tag</code> 和 <code>key</code>，两者都相同，则认为是相同节点，不再深度比较</li>
</ul>
<h2 id="简述-diff-算法过程"><a href="#简述-diff-算法过程" class="headerlink" title="简述 diff 算法过程"></a>简述 diff 算法过程</h2><p>在 Vue 中，主要是 <code>patch()</code>、<code>patchVnode()</code> 和 <code>updateChildren</code> 这三个方法来实现 <code>Diff</code> 的</p>
<ul>
<li><p>当 Vue 中的响应式数据发生变化时，就会触发 <code>updateCompoent()</code></p>
</li>
<li><p><code>updateComponent()</code> 会调用 <code>patch()</code> 方法，在该方法中进行比较，调用 <code>sameVnode</code> 判断是否为相同节点（判断 <code>key</code>、<code>tag</code> 等静态属性），如果是相同节点的话执行 <code>patchVnode</code> 方法，开始比较节点差异，如果不是相同节点的话，则进行替换操作</p>
<p><code>patch()</code> 接收新旧虚拟 DOM，即 <code>oldVnode</code>、<code>vnode</code></p>
<ul>
<li>首先判断 <code>vnode</code> 是否存在，如果不存在，删除旧节点</li>
<li>如果 <code>vnode</code> 存在，再判断 <code>oldVnode</code>，如果不存在，只需新增整个 <code>vnode</code> 即可</li>
<li>如果 <code>vnode</code> 和 <code>oldVnode</code> 都存在，判断两者是不是相同节点，如果是，调用 <code>patchVnode()</code> ，对两个节点进行详细比较</li>
<li>如果两者不是相同节点，只需将 <code>vnode</code> 转换为真实 DOM 替换 <code>oldVnode</code></li>
</ul>
</li>
<li><p><code>patchVnode</code> 同样接收新旧虚拟 DOM，即 <code>oldVnode</code>、<code>vnode</code></p>
<ul>
<li>首先判断两个虚拟 DOM 是不是全等，即没有任何变动，是的话直接结束函数，否者继续执行</li>
<li>其次更新节点的属性，接着判断 <code>vnode.text</code> 是否存在，存在的话只需更新节点文本即可，否则继续执行</li>
<li>判断 <code>vnode</code> 和 <code>oldVnode</code> 是否有孩子节点<ul>
<li>如果两者都有孩子节点，执行 <code>updateChildren()</code> ，进行比较更新</li>
<li>如果 <code>vnode</code> 有孩子，<code>oldVnode</code> 没有，则直接删除所有孩子节点，并将该文本属性设为空</li>
<li>如果 <code>oldVnode</code> 有孩子，<code>vnode</code> 没有，则直接删除所有孩子节点</li>
<li>如果两者都没有孩子节点，就判断 <code>oldVnode.text</code> 是否有内容，有的话情况内容即可</li>
</ul>
</li>
</ul>
</li>
<li><p><code>updateChildren</code> 接收三个参数：<code>parentElm</code> 父级真实节点、<code>oldCh</code> 为 <code>oldVnode</code> 的孩子节点、<code>newCh</code> 为 <code>Vnode</code> 的孩子节点</p>
<p><code>oldCh</code> 和 <code>newCh</code> 都是一个数组。正常我们想到的方法就是对这两个数组一一比较，时间复杂度为 <code>O(NM)</code>。Vue 中是通过四个指针实现的</p>
<ul>
<li>首先是 <code>oldStartVnode</code> 和 <code>newStartVnode</code> 进行比较（两头比较），如果比较相同的话，就可以执行 <code>patchVnode</code></li>
<li>如果 <code>oldStartVnode</code> 和 <code>newStartVnode</code> 匹配不上的话，接下来就是 <code>oldEndVnode</code> 和 <code>newEndVnode</code> 做比较了（两尾比较）</li>
<li>如果两头和两尾比较都不是相同节点的话，就开始交叉比较，首先是 <code>oldStartVnode</code> 和 <code>newEndVnode</code> 做比较（头尾比较）</li>
<li>如果 <code>oldStartVnode</code> 和 <code>newEndVnode</code> 匹配不上的话，就 <code>oldEndVnode</code> 和 <code>newStartVnode</code> 进行比较（尾头比较）</li>
</ul>
<p>如果这四种比较方法都匹配不到相同节点，才是用暴力解法，针对 <code>newStartVnode</code> 去遍历 <code>oldCh</code> 中剩余的节点，一一匹配</p>
</li>
</ul>
<blockquote>
<p>图片来源：<a target="_blank" rel="noopener" href="https://juejin.cn/post/6971622260490797069#heading-2">图文并茂地来详细讲讲Vue Diff算法</a></p>
</blockquote>
<p><img data-src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d84848aa035b4472b4d3f8e4b0d708c5~tplv-k3u1fbpfcp-watermark.awebp" alt="diff.jpg"></p>
<h2 id="Vue-为何是异步渲染，-nextTick-何用"><a href="#Vue-为何是异步渲染，-nextTick-何用" class="headerlink" title="Vue 为何是异步渲染，$nextTick 何用"></a>Vue 为何是异步渲染，$nextTick 何用</h2><ul>
<li>因为如果不采用异步更新，那么每次更新数据都会对当前组件进行重新渲染。异步渲染（合并 data 修改），再更新视图，可以提高渲染性能</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Watcher</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">update</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">this</span>.computed) &#123;</span><br><span class="line">      <span class="comment">// ...</span></span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="built_in">this</span>.sync) &#123;</span><br><span class="line">      <span class="comment">// ...</span></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 当数据发生变化时会将watcher放到一个队列中批量更新</span></span><br><span class="line">      queueWatcher(<span class="built_in">this</span>)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> queue: <span class="built_in">Array</span>&lt;Watcher&gt; = []</span><br><span class="line"><span class="keyword">let</span> has: &#123; [key: number]: ?<span class="literal">true</span> &#125; = &#123;&#125;</span><br><span class="line"><span class="keyword">let</span> waiting = <span class="literal">false</span></span><br><span class="line"><span class="keyword">let</span> flushing = <span class="literal">false</span></span><br><span class="line"><span class="comment">// 在派发更新时并不会每次修改都触发watcher的回调</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">queueWatcher</span>(<span class="params">watcher: Watcher</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> id = watcher.id</span><br><span class="line">  <span class="comment">// has对象保证同一个watcher只添加一次</span></span><br><span class="line">  <span class="keyword">if</span> (has[id] == <span class="literal">null</span>) &#123;</span><br><span class="line">    has[id] = <span class="literal">true</span></span><br><span class="line">    <span class="keyword">if</span> (!flushing) &#123;</span><br><span class="line">      queue.push(watcher)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">let</span> i = queue.length - <span class="number">1</span></span><br><span class="line">      <span class="keyword">while</span> (i &gt; index &amp;&amp; queue[i].id &gt; watcher.id) &#123;</span><br><span class="line">        i--</span><br><span class="line">      &#125;</span><br><span class="line">      queue.splice(i + <span class="number">1</span>, <span class="number">0</span>, watcher)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 通过waiting保证nextTick的调用逻辑只有一次</span></span><br><span class="line">    <span class="keyword">if</span> (!waiting) &#123;</span><br><span class="line">      waiting = <span class="literal">true</span></span><br><span class="line">      <span class="comment">// 调用nextTick方法 批量的进行更新</span></span><br><span class="line">      nextTick(flushSchedulerQueue)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">flushSchedulerQueue</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 1.因为父组件的创建过程是先于子的，所以watcher的创建也是先父后子，执行顺序也是先父后子</span></span><br><span class="line">  <span class="comment">// 2.用户自定义watcher要优先于渲染watcher执行</span></span><br><span class="line">  <span class="comment">// 3.如果一个组件在父组件watcher执行期间被销毁，那么它对应的watcher执行都可以被跳过</span></span><br><span class="line">  queue.sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> a.id - b.id) <span class="comment">// 由小到大</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p><code>$nextTick</code> 在 DOM 更新完之后，触发回调，用于获得更新后的 DOM</p>
</li>
<li><p><code>$nextTick</code> 方法主要是使用了 <strong>宏任务</strong> 和 <strong>微任务</strong>，定义一个异步方法，多次调用 <code>nextTick</code> 会将方法存入队列中，通过这个异步方法清空当前队列</p>
<p>Vue 2.4 之前都是使用微任务，但是微任务的优先级过高，有些情况下可能会出现比事件冒泡更快的情况，但如果都是用宏任务，有可能会出现渲染的性能问题</p>
<p>新版，默认使用微任务，但在特殊情况下会使用宏任务，比如：<code>v-on</code></p>
</li>
<li><p>对于实现宏任务，会先判断是否能用 <code>setImmediate</code>，不能的话降级为 <code>MessageChannel</code> ，以上都不行的话就是用 <code>setTimeout</code></p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (<span class="keyword">typeof</span> setImmediate !== <span class="string">&#x27;undefined&#x27;</span> &amp;&amp; isNative(setImmediate)) &#123;</span><br><span class="line">  macroTimerFunc = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    setImmediate(flushCallbacks)</span><br><span class="line">  &#125;</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (</span><br><span class="line">  <span class="keyword">typeof</span> MessageChannel !== <span class="string">&#x27;undefined&#x27;</span> &amp;&amp;</span><br><span class="line">  (isNative(MessageChannel) ||</span><br><span class="line">    <span class="comment">// PhantomJS</span></span><br><span class="line">    MessageChannel.toString() === <span class="string">&#x27;[object MessageChannelConstructor]&#x27;</span>)</span><br><span class="line">) &#123;</span><br><span class="line">  <span class="keyword">const</span> channel = <span class="keyword">new</span> MessageChannel()</span><br><span class="line">  <span class="keyword">const</span> port = channel.port2</span><br><span class="line">  channel.port1.onmessage = flushCallbacks</span><br><span class="line">  macroTimerFunc = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    port.postMessage(<span class="number">1</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  macroTimerFunc = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(flushCallbacks, <span class="number">0</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Vue-常见性能优化方式"><a href="#Vue-常见性能优化方式" class="headerlink" title="Vue 常见性能优化方式"></a>Vue 常见性能优化方式</h2><ul>
<li>合理使用 <code>v-show</code> 和 <code>v-if</code></li>
<li>合理使用 <code>computed</code></li>
<li><code>v-for</code> 时加 <code>key</code>（Vue 会进行复用），以及避免和 <code>v-if</code> 同时使用</li>
<li>自定义事件、DOM 事件及时销毁</li>
<li>合理使用异步组件、路由懒加载</li>
<li>合理使用 <code>keep-alive</code>（SPA 页面）</li>
<li><code>data</code> 层级不要太深，不要讲所有数据都放在 <code>data</code> 中（会增加 <code>getter</code> 和 <code>setter</code>，收集对应 <code>watcher</code>）</li>
<li>使用 <code>vue-loader</code> 在开发环境做模板编译（预编译）</li>
<li>webpack 层面的优化</li>
<li>前端通用的性能优化，如图片懒加载、防抖、节流</li>
<li>使用 SSR</li>
</ul>
<h2 id="释义参数-vue-template-compiler"><a href="#释义参数-vue-template-compiler" class="headerlink" title="释义参数 vue-template-compiler"></a>释义参数 vue-template-compiler</h2><ul>
<li><code>render</code> 中的参数释义</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">_c = createElement</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">installRenderHelpers</span>(<span class="params">target</span>) </span>&#123;</span><br><span class="line">  target._o = markOnce</span><br><span class="line">  target._n = toNumber</span><br><span class="line">  target._s = toString</span><br><span class="line">  target._l = renderList</span><br><span class="line">  target._t = renderSlot</span><br><span class="line">  target._q = looseEqual</span><br><span class="line">  target._i = looseIndexOf</span><br><span class="line">  target._m = renderStatic</span><br><span class="line">  target._f = resolveFilter</span><br><span class="line">  target._k = checkKeyCodes</span><br><span class="line">  target._b = bindObjectProps</span><br><span class="line">  target._v = createTextVNode</span><br><span class="line">  target._e = createEmptyVNode</span><br><span class="line">  target._u = resolveScopedSlots</span><br><span class="line">  target._g = bindObjectListeners</span><br><span class="line">  target._d = bindDynamicKeys</span><br><span class="line">  target._p = prependModifier</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    

	<div>
		  
			
<div class="my_post_copyright clearfix">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <article class="box-left">
    <img src="https://gitee.com/lilyn/pic/raw/master/logo.jpg">
  </article>
  <article class="box-right">
    <p><span>本文标题:</span><a href="/posts/920f26b5/">Vue2 面试题</a></p>
    <p><span>文章作者:</span><a href="/" title="访问 LiLyn 的个人博客">LiLyn</a></p>
    <p><span>原始链接:</span><a href="/posts/920f26b5/" title="Vue2 面试题">http://llmysnow.top/posts/920f26b5/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://llmysnow.top/posts/920f26b5/"  aria-label="复制成功！"></i></span>
  </p>
    <p><span>许可协议:</span>转载请保留原文链接及作者。</p>  
  </article>
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>

		  
	</div>

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Vue/" rel="tag"><i class="fa fa-tag"></i> Vue</a>
              <a href="/tags/diff%E7%AE%97%E6%B3%95/" rel="tag"><i class="fa fa-tag"></i> diff算法</a>
              <a href="/tags/%E5%93%8D%E5%BA%94%E5%BC%8F%E5%8E%9F%E7%90%86/" rel="tag"><i class="fa fa-tag"></i> 响应式原理</a>
              <a href="/tags/nextTick/" rel="tag"><i class="fa fa-tag"></i> nextTick</a>
          </div>
		 
		<!--post-tags 彩色标签-->
		<script type="text/javascript">
		var tagsall=document.getElementsByClassName("post-tags")
		for (var i = tagsall.length - 1; i >= 0; i--){
			var tags=tagsall[i].getElementsByTagName("a");
			for (var j = tags.length - 1; j >= 0; j--) {
				var r=Math.floor(Math.random()*75+130);
				var g=Math.floor(Math.random()*75+100);
				var b=Math.floor(Math.random()*75+80);
				tags[j].style.background = "rgb("+r+","+g+","+b+")";
				tags[j].style.color = "#fff";
				tags[j].style.padding = "0 10px";
			}
		}                        
		</script>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/735a614e/" rel="prev" title="VScode 前端常用配置/设置/问题">
      <i class="fa fa-chevron-left"></i> VScode 前端常用配置/设置/问题
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/5381f975/" rel="next" title="Vue3 面试题">
      Vue3 面试题 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#v-show-%E5%92%8C-v-if-%E5%8C%BA%E5%88%AB"><span class="nav-text">v-show 和 v-if 区别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%BA%E4%BD%95%E5%9C%A8-v-for-%E4%B8%AD%E7%94%A8-key"><span class="nav-text">为何在 v-for 中用 key</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8F%8F%E8%BF%B0-Vue-%E7%BB%84%E4%BB%B6%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%EF%BC%88%E7%88%B6%E5%AD%90%E7%BB%84%E4%BB%B6%EF%BC%89"><span class="nav-text">描述 Vue 组件生命周期（父子组件）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Vue-%E7%BB%84%E4%BB%B6%E5%A6%82%E4%BD%95%E9%80%9A%E8%AE%AF"><span class="nav-text">Vue 组件如何通讯</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8F%8F%E8%BF%B0%E7%BB%84%E4%BB%B6%E6%B8%B2%E6%9F%93%E5%92%8C%E6%9B%B4%E6%96%B0%E8%BF%87%E7%A8%8B"><span class="nav-text">描述组件渲染和更新过程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%8C%E5%90%91%E6%95%B0%E6%8D%AE%E7%BB%91%E5%AE%9A-v-model-%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86"><span class="nav-text">双向数据绑定 v-model 的实现原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AF%B9-MVVM-%E7%9A%84%E7%90%86%E8%A7%A3"><span class="nav-text">对 MVVM 的理解</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#computed-%E5%92%8C-watch-%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-text">computed 和 watch 的区别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%BA%E4%BD%95%E7%BB%84%E4%BB%B6-data-%E5%BF%85%E9%A1%BB%E6%98%AF%E4%B8%80%E4%B8%AA%E5%87%BD%E6%95%B0"><span class="nav-text">为何组件 data 必须是一个函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89-v-model"><span class="nav-text">自定义 v-model</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%9B%B8%E5%90%8C%E9%80%BB%E8%BE%91%E5%A6%82%E4%BD%95%E6%8A%BD%E7%A6%BB"><span class="nav-text">相同逻辑如何抽离</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%95%E6%97%B6%E4%BD%BF%E7%94%A8%E5%BC%82%E6%AD%A5%E7%BB%84%E4%BB%B6"><span class="nav-text">何时使用异步组件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%95%E6%97%B6%E4%BD%BF%E7%94%A8-keep-alive"><span class="nav-text">何时使用 keep-alive</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%95%E6%97%B6%E9%9C%80%E8%A6%81%E4%BD%BF%E7%94%A8-beforeDestory"><span class="nav-text">何时需要使用 beforeDestory</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#action-%E5%92%8C-mutation-%E6%9C%89%E4%BD%95%E5%8C%BA%E5%88%AB"><span class="nav-text">action 和 mutation 有何区别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#vue-router-%E5%B8%B8%E7%94%A8%E7%9A%84%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%BC%8F"><span class="nav-text">vue-router 常用的路由模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#vnode-%E6%8F%8F%E8%BF%B0%E4%B8%80%E4%B8%AA-DOM-%E7%BB%93%E6%9E%84"><span class="nav-text">vnode 描述一个 DOM 结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E5%93%8D%E5%BA%94%E5%BC%8F%E5%8E%9F%E7%90%86"><span class="nav-text">数据响应式原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#diff-%E7%AE%97%E6%B3%95"><span class="nav-text">diff 算法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AE%80%E8%BF%B0-diff-%E7%AE%97%E6%B3%95%E8%BF%87%E7%A8%8B"><span class="nav-text">简述 diff 算法过程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Vue-%E4%B8%BA%E4%BD%95%E6%98%AF%E5%BC%82%E6%AD%A5%E6%B8%B2%E6%9F%93%EF%BC%8C-nextTick-%E4%BD%95%E7%94%A8"><span class="nav-text">Vue 为何是异步渲染，$nextTick 何用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Vue-%E5%B8%B8%E8%A7%81%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E6%96%B9%E5%BC%8F"><span class="nav-text">Vue 常见性能优化方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%87%8A%E4%B9%89%E5%8F%82%E6%95%B0-vue-template-compiler"><span class="nav-text">释义参数 vue-template-compiler</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="LiLyn"
      src="/images/logo.jpg">
  <p class="site-author-name" itemprop="name">LiLyn</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">70</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">162</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/llwodexue" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;llwodexue" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/qq_38689395" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;qq_38689395" rel="noopener" target="_blank"><i class="fas fa-copyright fa-fw"></i>CSDN</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://scx69.gitee.io/blogs/" title="https:&#x2F;&#x2F;scx69.gitee.io&#x2F;blogs&#x2F;" rel="noopener" target="_blank">花开满城</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://yixin-oss.gitee.io/daytoy/" title="http:&#x2F;&#x2F;yixin-oss.gitee.io&#x2F;daytoy&#x2F;" rel="noopener" target="_blank">daytoy</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LiLyn</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">463k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">7:01</span>
</div>

<!--
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>-->

<!--
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="powered-by">
  <i class="fa fa-user-md"></i>
  <span id="busuanzi_container_site_pv">
    本站访问量:<span id="busuanzi_value_site_pv"></span>次
  </span>
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_container_site_uv">
    本站总访客量：<span id="busuanzi_value_site_uv"></span>人
  </span>
</div>-->

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













  

  

  <!-- 动态线条背景 -->
  <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  <!-- 页面点击小红心 -->
  <script type="text/javascript">
	!function(e,t,a){function n(){c(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"),o(),r()}function r(){for(var e=0;e<d.length;e++)d[e].alpha<=0?(t.body.removeChild(d[e].el),d.splice(e,1)):(d[e].y--,d[e].scale+=.004,d[e].alpha-=.013,d[e].el.style.cssText="left:"+d[e].x+"px;top:"+d[e].y+"px;opacity:"+d[e].alpha+";transform:scale("+d[e].scale+","+d[e].scale+") rotate(45deg);background:"+d[e].color+";z-index:99999");requestAnimationFrame(r)}function o(){var t="function"==typeof e.onclick&&e.onclick;e.onclick=function(e){t&&t(),i(e)}}function i(e){var a=t.createElement("div");a.className="heart",d.push({el:a,x:e.clientX-5,y:e.clientY-5,scale:1,alpha:1,color:s()}),t.body.appendChild(a)}function c(e){var a=t.createElement("style");a.type="text/css";try{a.appendChild(t.createTextNode(e))}catch(t){a.styleSheet.cssText=e}t.getElementsByTagName("head")[0].appendChild(a)}function s(){return"rgb("+~~(255*Math.random())+","+~~(255*Math.random())+","+~~(255*Math.random())+")"}var d=[];e.requestAnimationFrame=function(){return e.requestAnimationFrame||e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(e){setTimeout(e,1e3/60)}}(),n()}(window,document);
  </script>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body>
</html>